package job

import (
	"context"
	"gitee.com/crack007/goose"
	"gitee.com/crack007/goose/schedule"
	"github.com/crack007/go-im/pb"
	"github.com/crack007/go-im/src/common/model"
	"time"
)

type NodePingJob struct {
	schedule.DefaultJob
	client          pb.NodeServiceClient
	source          *model.SentinelModel
	target          *model.NodeModel
	timeoutCallback func(target *model.NodeModel)
}

func NewNodePingJob(client pb.NodeServiceClient, source *model.SentinelModel, targetId *model.NodeModel, timeoutCallback func(target *model.NodeModel)) *NodePingJob {
	return &NodePingJob{
		DefaultJob: schedule.DefaultJob{
			JobDelay: 5000,
		},
		client:          client,
		target:          targetId,
		source:          source,
		timeoutCallback: timeoutCallback,
	}
}

func (d *NodePingJob) Run(task *schedule.Task) {
	// TODO 监控节点下线或异常处理
	resp, err := d.client.OnPing(context.Background(), &pb.PingReq{SourceId: d.source.Id, TargetId: d.target.Id})
	if err != nil {
		d.Cancel()
		d.timeoutCallback(d.target)
		return
	}
	d.target.LastConnected = time.Now().Unix()
	goose.GetLogger().Trace("Node pong->id:%s", resp.SourceId)
}

func (d *NodePingJob) IsCron() bool {
	return true
}
